package com.cinema.servlet.booking;

import com.cinema.dao.OrderDAO;
import com.cinema.dao.ShowtimeDAO;
import com.cinema.entity.Order;
import com.cinema.entity.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 支付Servlet
 */
public class PaymentServlet extends HttpServlet {
    private OrderDAO orderDAO = new OrderDAO();
    private ShowtimeDAO showtimeDAO = new ShowtimeDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String orderNo = request.getParameter("orderNo");

        if (orderNo == null || orderNo.trim().isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/user/orders");
            return;
        }

        try {
            // 获取订单信息
            Order order = orderDAO.findByOrderNo(orderNo);
            if (order == null) {
                request.setAttribute("error", "订单不存在");
                request.getRequestDispatcher("/error/404.jsp").forward(request, response);
                return;
            }

            // 检查订单所有者
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("user");
            if (!order.getUserId().equals(user.getId())) {
                request.setAttribute("error", "无权访问此订单");
                request.getRequestDispatcher("/error/403.jsp").forward(request, response);
                return;
            }

            // 检查订单状态
            if (!"PENDING".equals(order.getStatus())) {
                if ("PAID".equals(order.getStatus())) {
                    response.sendRedirect(request.getContextPath() + "/user/orders");
                    return;
                } else {
                    request.setAttribute("error", "订单状态异常，无法支付");
                    request.getRequestDispatcher("/error/order-invalid.jsp").forward(request, response);
                    return;
                }
            }

            // 检查订单是否过期
            if (order.isExpired()) {
                // 更新订单状态为过期
                orderDAO.updateOrderStatus(order.getId(), "EXPIRED");
                // 恢复座位数
                showtimeDAO.increaseAvailableSeats(order.getShowtimeId(), order.getTicketCount());

                request.setAttribute("error", "订单已过期，请重新下单");
                request.getRequestDispatcher("/error/order-expired.jsp").forward(request, response);
                return;
            }

            request.setAttribute("order", order);
            request.getRequestDispatcher("/payment.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "获取支付信息失败");
            request.getRequestDispatcher("/error/500.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String action = request.getParameter("action");

        if ("pay".equals(action)) {
            handlePayment(request, response);
        } else if ("cancel".equals(action)) {
            handleCancel(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/user/orders");
        }
    }

    /**
     * 处理支付
     */
    private void handlePayment(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String orderNo = request.getParameter("orderNo");
        String paymentMethod = request.getParameter("paymentMethod");
        String paymentPassword = request.getParameter("paymentPassword");

        try {
            // 获取订单信息
            Order order = orderDAO.findByOrderNo(orderNo);
            if (order == null || !"PENDING".equals(order.getStatus())) {
                request.setAttribute("error", "订单状态异常");
                doGet(request, response);
                return;
            }

            // 检查订单是否过期
            if (order.isExpired()) {
                orderDAO.updateOrderStatus(order.getId(), "EXPIRED");
                showtimeDAO.increaseAvailableSeats(order.getShowtimeId(), order.getTicketCount());

                request.setAttribute("error", "订单已过期");
                doGet(request, response);
                return;
            }

            // 验证支付密码（模拟）
            if (!"123456".equals(paymentPassword)) {
                request.setAttribute("error", "支付密码错误");
                request.setAttribute("order", order);
                request.getRequestDispatcher("/payment.jsp").forward(request, response);
                return;
            }

            // 模拟支付处理
            boolean paymentSuccess = simulatePayment(paymentMethod);

            if (paymentSuccess) {
                // 更新订单状态为已支付
                boolean updateSuccess = orderDAO.payOrder(orderNo, paymentMethod);

                if (updateSuccess) {
                    // 支付成功，跳转到成功页面
                    response.sendRedirect(request.getContextPath() + "/user/payment-success?orderNo=" + orderNo);
                } else {
                    request.setAttribute("error", "支付处理失败，请稍后重试");
                    doGet(request, response);
                }
            } else {
                request.setAttribute("error", "支付失败，请检查支付方式或稍后重试");
                doGet(request, response);
            }

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "支付过程中发生错误");
            doGet(request, response);
        }
    }

    /**
     * 处理取消订单
     */
    private void handleCancel(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String orderNo = request.getParameter("orderNo");

        try {
            System.out.println("开始处理取消订单，订单号: " + orderNo);

            // 获取订单信息
            Order order = orderDAO.findByOrderNo(orderNo);
            if (order == null) {
                System.err.println("订单不存在: " + orderNo);
                request.setAttribute("error", "订单不存在");
                doGet(request, response);
                return;
            }

            if (!"PENDING".equals(order.getStatus())) {
                System.err.println("订单状态异常: " + order.getStatus());
                request.setAttribute("error", "订单状态异常，只能取消待支付的订单");
                doGet(request, response);
                return;
            }

            System.out.println("订单信息正常，开始取消订单");

            // 取消订单
            boolean cancelSuccess = orderDAO.updateOrderStatus(order.getId(), "CANCELLED");

            if (cancelSuccess) {
                System.out.println("订单取消成功，恢复座位数");
                // 恢复座位数
                showtimeDAO.increaseAvailableSeats(order.getShowtimeId(), order.getTicketCount());

                // 跳转到订单列表（URL编码中文消息）
                try {
                    String message = URLEncoder.encode("订单已取消", "UTF-8");
                    String redirectUrl = request.getContextPath() + "/user/orders?message=" + message;
                    System.out.println("准备跳转到: " + redirectUrl);
                    response.sendRedirect(redirectUrl);
                } catch (Exception ex) {
                    System.err.println("URL编码失败: " + ex.getMessage());
                    // 如果编码失败，使用不带消息的跳转
                    String redirectUrl = request.getContextPath() + "/user/orders";
                    System.out.println("降级跳转到: " + redirectUrl);
                    response.sendRedirect(redirectUrl);
                }
            } else {
                System.err.println("取消订单失败");
                request.setAttribute("error", "取消订单失败");
                doGet(request, response);
            }

        } catch (Exception e) {
            System.err.println("取消订单过程中发生异常:");
            e.printStackTrace();
            request.setAttribute("error", "取消订单过程中发生错误: " + e.getMessage());
            doGet(request, response);
        }
    }

    /**
     * 模拟支付处理
     */
    private boolean simulatePayment(String paymentMethod) {
        try {
            // 模拟网络延迟
            Thread.sleep(1000);

            // 模拟支付成功率（95%成功率）
            return Math.random() < 0.95;

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }
}
